﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

using AUV5.Common;

namespace AUV5.Web.Pages
{
    public partial class UserProfile : PageBaseFrontend
    {
        //关于切图变量

        private int imgHeight = CommonDefine.USER_IMG_HEIGHT;
        private int imgWidth = CommonDefine.USER_IMG_WIDTH;
        private int minHeight = CommonDefine.USER_IMG_MINHEIGHT;
        private int minWidth = CommonDefine.USER_IMG_MINWIDTH;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    if (base.IsVerified)
                    {
                        //绑定省市
                        this.BindProvince();
                        this.BindCity();

                        DataBindDetail();

                        showImages("", imgHeight, imgHeight);
                    }
                    else
                    {
                        Response.Redirect(URL_INDEX);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        #region  显示省市及其他个人信息
        private void BindProvince()
        {
            base.SetGBAD(this.ddlProvince, "1");
            this.ddlProvince.Items.Insert(0, new ListItem("请选择", ""));
            this.ddlProvince.Items[0].Selected = true;
        }

        private void BindCity()
        {
            if (!string.IsNullOrEmpty(this.ddlProvince.SelectedValue))
            {
                this.SetGBAD(this.ddlCity, this.ddlProvince.SelectedValue);
            }
            else
            {
                this.ddlCity.Items.Clear();
                this.ddlCity.Items.Insert(0, new ListItem("请选择", ""));
            }
        }

        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindCity();
        }

        
        //显示信息到页面
        void DataBindDetail()
        {
            Model.UserInfo user = base.VerifiedInfo.User;
            txbName.Text = user.RealName;
            txbEmail.Text = user.Email;
            txbDescription.Text = user.Description;
            string PhotoPath = user.PhotoPath;
            if (PhotoPath != string.Empty)
            {
                string imgPath = "~" + user.PhotoPath;
                imgCut.ImageUrl = imgPath;
            }
            ckbReceive.Checked = user.ReceiveDigest;
            txbAddress.Text = user.Address;

            //显示用户省信息
            if (this.ddlProvince.Items.FindByValue(user.Province) != null)
            {
                this.ddlProvince.SelectedItem.Selected = false;
                this.ddlProvince.Items.FindByValue(user.Province).Selected = true;
            }

            this.BindCity();

            if (this.ddlCity.Items.FindByValue(user.City) != null)
            {
                this.ddlCity.SelectedItem.Selected = false;
                this.ddlCity.Items.FindByValue(user.City).Selected = true;
            }
        }
        #endregion

        #region 更新密码
        protected void imgbtnSave1_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                Model.UserInfo user = base.VerifiedInfo.User;
                if (user != null)
                {
                    if (txbNewpassord.Text.Trim() != txbRePassword.Text.Trim())
                    {
                        lblMessage.Text = "两次密码输入不一致";
                        return;
                    }
                    string oldPwd = base.EncryptMD5(txbOldPwd.Text.Trim());
                    if (oldPwd != user.Password)
                    {
                        lblMessage.Text = "您输入的密码有误";
                        divChange.Attributes["style"] = "display:block";
                        return;
                    }
                    else
                        user.Password = base.EncryptMD5(txbRePassword.Text.Trim());
                    //更新信息
                    if (BLL.UserInfoBLL.Instance.Update(user) == 1)
                    {
                        base.Alert("密码修改成功");
                        hfIsChange.Value = "no";
                    }
                    else
                        base.Alert("修改失败");
                }
                else
                {
                    AlertGo("请登录", "Index.aspx");
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {

            }
        }
        #endregion

        #region 更新个人信息
        protected void imgbtnSave0_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                Model.UserInfo user = base.VerifiedInfo.User;
                if (user != null)
                {
                    string realName = txbName.Text.Trim();
                    string email = txbEmail.Text.Trim();
                    //个人描述要进行敏感词过虑
                    string description = txbDescription.Text.Trim();
                    BadWordsFilter.Instance.FindAndReplace(ref description,'*');
                    string address = txbAddress.Text.Trim();
                    bool digest = ckbReceive.Checked;
                    user.RealName = realName;
                    user.Email = email;
                    user.Description = description;
                    user.Address = address;
                    user.Province = ddlProvince.SelectedValue;
                    user.City = ddlCity.SelectedValue;
                    user.ReceiveDigest = digest;

                    string oldPhoto = user.PhotoPath;

                    //移动图片
                    if (hfIsChange.Value == "yes")
                    {
                        MoveTmp();
                        user.PhotoPath = base.GetDirectoryOfDate(false) + user.UserName + Convert.ToString(ViewState["ext"]);
                    }


                    //更新信息
                    if (BLL.UserInfoBLL.Instance.Update(user) == 1)
                    {
                        if (hfIsChange.Value == "yes")
                        {
                            //删除临时路径下的文件
                            //todo:
                            string dir = GetDirectoryOfDate(true);

                            string[] tmpArr = Directory.GetFiles(Server.MapPath(dir), "*_" + user.UserName + ".*", SearchOption.TopDirectoryOnly);
                            foreach (string tmpDir in tmpArr)
                            {
                                FileInfo tmpFile = new FileInfo(tmpDir);
                                tmpFile.Delete();
                            }

                            //删除原头像文件（若原头像文件未被删除且未被替换)
                            //排除修改之前头像为空的情况
                            if (oldPhoto != "" && user.PhotoPath != oldPhoto && oldPhoto != "/!images/avatar.jpg")
                            {
                                if (System.IO.File.Exists(Server.MapPath(oldPhoto)))
                                {
                                    System.IO.File.Delete(Server.MapPath(oldPhoto));
                                }
                            }
                        }

                        base.AlertGo("更新成功", "UserProfile.aspx");
                        hfIsChange.Value = "no";
                    }
                    else
                        base.AlertGo("更新失败", "UserProfile.aspx");

                    divChange.Attributes["style"] = "display:none";

                    Response.Redirect(Request.Url.ToString());
                }
                else
                {
                    AlertGo("请登录", "Index.aspx");
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            { 
            
            }
        }
        #endregion

        #region  上传图片
        protected void btnUploadThumbPic_Click(object sender, EventArgs e)
        {
            string imgName = fulImg.FileName;                       //原图名

            System.Drawing.Image img = null;   //存原图

            System.Drawing.Image oldThumbIamge = null;  //原图缩放

            try
            {
                if (imgName != null)
                {                   
                    string ext = System.IO.Path.GetExtension(imgName).ToLower();      //原图后缀

                    ViewState["ext"] = ext;

                    if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
                    {
                        Model.UserInfo user = base.VerifiedInfo.User;

                        string dir = GetDirectoryOfDate(true);

                        //若不存在日期形成的目录，创建
                        if (!System.IO.Directory.Exists(Request.PhysicalApplicationPath + dir))
                        {
                            System.IO.Directory.CreateDirectory(Request.PhysicalApplicationPath + dir);
                        }

                        string path = dir + "original_" + user.UserName + ext;            //原图上传路径

                        fulImg.SaveAs(Server.MapPath(path));                  //上传原图        

                        img = System.Drawing.Image.FromFile(Server.MapPath(path));       //读取原图到Image对象

                        int oldHeight = img.Height;   //原图高
                        int oldWidth = img.Width;     //原图宽


                        if (oldHeight >= imgHeight && oldWidth >= imgWidth)        //上传图片宽高都大于等于设定高度
                        {

                            int oldThumbImageHeight = 0;   //缩放后高
                            int oldThumbImageWidth = 0;   //缩放后的宽

                            string newThumbPath = dir + "thumb_" + user.UserName + ext;

                            ViewState["newThumbPath"] = newThumbPath;


                            if (oldHeight > oldWidth)
                            {
                                oldThumbImageWidth = Convert.ToInt32(Convert.ToDouble(imgHeight) / Convert.ToDouble(oldHeight) * oldWidth);
                                oldThumbImageHeight = imgHeight;

                                if (oldThumbImageWidth >= minWidth)
                                {
                                    oldThumbIamge = GetThumbNailImage(img, imgWidth, imgHeight);
                                    oldThumbIamge.Save(Server.MapPath(newThumbPath));
                                }
                                else
                                {
                                    //这里缺少删除上传图片方法
                                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片长宽比不符合标准')</script>");
                                }
                            }
                            else
                            {
                                oldThumbImageHeight = Convert.ToInt32(Convert.ToDouble(imgWidth) / Convert.ToDouble(oldWidth) * oldHeight);
                                oldThumbImageWidth = imgWidth;

                                if (oldThumbImageHeight >= minHeight)
                                {
                                    oldThumbIamge = GetThumbNailImage(img, imgWidth, imgHeight);
                                    oldThumbIamge.Save(Server.MapPath(newThumbPath));
                                }
                                else
                                {
                                    //这里缺少删除上传图片方法
                                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片长宽比不符合标准')</script>");
                                }
                            }

                            if (oldThumbImageHeight > oldThumbImageWidth)
                            {
                                maxVal.Value = Convert.ToString(oldThumbImageWidth);
                            }
                            else
                            {
                                maxVal.Value = Convert.ToString(oldThumbImageHeight);
                            }

                            showImages(newThumbPath, oldThumbImageWidth, oldThumbImageHeight);  //显示缩放后的                   

                        }
                        else
                        {
                            //这里缺少删除上传图片方法
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('宽高都要大于300')</script>");
                        }

                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式不符合要求')</script>");
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                
                if (oldThumbIamge != null)
                {
                    oldThumbIamge.Dispose();
                }
                if (img != null)
                {
                    img.Dispose();
                }
                GC.Collect();

            }

        }


        #endregion

        #region 加载图片
        /// <summary>
        /// 加载图片
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <param name="imgwidth">图片宽度</param>
        /// <param name="imgheight">图片高度</param>
        public void showImages(string imagePath, int imgwidth, int imgheight)
        {
            System.Text.StringBuilder sb = new StringBuilder();

            sb.Append("<script type=\"text/javascript\">");

            sb.Append("window.onload = function ShowImg(){");

            if (!string.IsNullOrEmpty(imagePath))
                sb.Append("var imagePath1=\"" + imagePath + "\";");
            else
                sb.Append("var imagePath1=" + "\"/!images/ef_pic.jpg\";");

            sb.Append("var ic = new ImgCropper(\"bgDiv\", \"dragDiv\", imagePath1, " + imgwidth + ", " + imgheight + ", {");

            sb.Append("Right: \"rRight\", Left: \"rLeft\", Up: \"rUp\", Down: \"rDown\",");

            sb.Append("RightDown: \"rRightDown\", LeftDown: \"rLeftDown\", RightUp: \"rRightUp\", LeftUp: \"rLeftUp\"");

            sb.Append("});");

            sb.Append("}");

            sb.Append("</script>");

            Page.ClientScript.RegisterStartupScript(this.GetType(), "LoadPicScript", sb.ToString());

        }
        #endregion

        #region 切图
        protected void btnSure_Click(object sender, EventArgs e)
        {
            System.Drawing.Image thumbImageSmall = null;  //存缩放图（100*100）

            System.Drawing.Graphics gps = null;    //存绘图对象   

            System.Drawing.Bitmap bitmap = null;  //生成图像

            System.Drawing.Image oldThumbIamge = null;  //原图缩放

            try
            {
                if (ViewState["newThumbPath"] != null && ViewState["ext"] != null)
                {
                    bitmap = new System.Drawing.Bitmap(Convert.ToInt32(maxVal.Value), Convert.ToInt32(maxVal.Value));

                    oldThumbIamge = System.Drawing.Image.FromFile(Server.MapPath(Convert.ToString(ViewState["newThumbPath"])));

                    System.Drawing.Rectangle rl = new System.Drawing.Rectangle(Convert.ToInt32(x.Value), Convert.ToInt32(y.Value), Convert.ToInt32(maxVal.Value), Convert.ToInt32(maxVal.Value));   //得到截图矩形
                  
                    gps = System.Drawing.Graphics.FromImage(bitmap);      //读到绘图对象

                    gps.DrawImage(oldThumbIamge, 0, 0, rl, System.Drawing.GraphicsUnit.Pixel);


                    Model.UserInfo user = base.VerifiedInfo.User;
                    
                    string dir = GetDirectoryOfDate(true);

                    //若不存在日期形成的目录，创建
                    if (!System.IO.Directory.Exists(Request.PhysicalApplicationPath + dir))
                    {
                        System.IO.Directory.CreateDirectory(Request.PhysicalApplicationPath + dir);
                    }
                    string bitmapPath = Server.MapPath(dir + "cut_" + user.UserName + Convert.ToString(ViewState["ext"]));

                    bitmap.Save(bitmapPath);

                    thumbImageSmall = System.Drawing.Image.FromFile(bitmapPath);
                    
                    string finalPath = dir + "final_" + user.UserName + Convert.ToString(ViewState["ext"]);

                    string cutPath = Server.MapPath(finalPath);

                    thumbImageSmall = GetThumbNailImage(thumbImageSmall, minWidth, minHeight);
                    thumbImageSmall.Save(cutPath);

                    imgCut.ImageUrl = finalPath;
                    hfIsChange.Value = "yes";
                }


            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {

                if (thumbImageSmall != null)
                {                    
                    thumbImageSmall.Dispose();
                }
                if (gps != null)
                {
                    gps.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (oldThumbIamge != null)
                {
                    oldThumbIamge.Dispose();
                }
                GC.Collect();
            }
        }
        #endregion

        #region 生成一个指定大小的缩略图
        ///<summary>
        /// 对给定的一个图片（Image对象）生成一个指定大小的缩略图。
        ///</summary>
        ///<param name="originalImage">原始图片</param>
        ///<param name="thumMaxWidth">缩略图的宽度</param>
        ///<param name="thumMaxHeight">缩略图的高度</param>
        ///<returns>返回缩略图的Image对象</returns>
        public static System.Drawing.Image GetThumbNailImage(System.Drawing.Image originalImage, int thumMaxWidth, int thumMaxHeight)
        {
            System.Drawing.Size thumRealSize = System.Drawing.Size.Empty;
            System.Drawing.Image newImage = originalImage;
            System.Drawing.Graphics graphics = null;
            try
            {
                thumRealSize = GetNewSize(thumMaxWidth, thumMaxHeight, originalImage.Width, originalImage.Height);
                newImage = new System.Drawing.Bitmap(thumRealSize.Width, thumRealSize.Height);
                graphics = System.Drawing.Graphics.FromImage(newImage);
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.Clear(System.Drawing.Color.Transparent);
                graphics.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new System.Drawing.Rectangle(0, 0, originalImage.Width, originalImage.Height), System.Drawing.GraphicsUnit.Pixel);
            }
            catch { }
            finally
            {
                if (graphics != null)
                {
                    graphics.Dispose();
                    graphics = null;
                }
            }
            return newImage;
        }
        #endregion

        #region 获取一个图片按等比例缩小后的大小

        ///<summary>
        /// 获取一个图片按等比例缩小后的大小。
        ///</summary>
        ///<param name="maxWidth">需要缩小到的宽度</param>
        ///<param name="maxHeight">需要缩小到的高度</param>
        ///<param name="imageOriginalWidth">图片的原始宽度</param>
        ///<param name="imageOriginalHeight">图片的原始高度</param>
        ///<returns>返回图片按等比例缩小后的实际大小</returns>
        public static System.Drawing.Size GetNewSize(int maxWidth, int maxHeight, int imageOriginalWidth, int imageOriginalHeight)
        {
            double w = 0.0;
            double h = 0.0;
            double sw = Convert.ToDouble(imageOriginalWidth);
            double sh = Convert.ToDouble(imageOriginalHeight);
            double mw = Convert.ToDouble(maxWidth);
            double mh = Convert.ToDouble(maxHeight);
            if (sw < mw && sh < mh)
            {
                w = sw;
                h = sh;
            }
            else if ((sw / sh) > (mw / mh))
            {
                w = maxWidth;
                h = (w * sh) / sw;
            }
            else
            {
                h = maxHeight;
                w = (h * sw) / sh;
            }
            return new System.Drawing.Size(Convert.ToInt32(w), Convert.ToInt32(h));
        }
        #endregion

        #region 剪切头像到真正的目录下
        void MoveTmp()
        {
            Model.UserInfo user = base.VerifiedInfo.User;
            string oldphoto = user.PhotoPath;

            string path = Server.MapPath(GetDirectoryOfDate(false));
            string tmpPath = Server.MapPath(GetDirectoryOfDate(true));

            //图片路径处理
            string relativePath = GetDirectoryOfDate(true)+"final_" + user.UserName + Convert.ToString(ViewState["ext"]);
            
            string tmpFilePath = Server.MapPath(relativePath);
            //若不存在目录，创建
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }

            //文件最终路径
            string fileDir = path + user.UserName + Convert.ToString(ViewState["ext"]);
            FileInfo oldfile = new FileInfo(fileDir);

            //若目录存在，删除,否则会有异常
            if (oldfile.Exists)
                oldfile.Delete();

            //1.剪切头像到真正的目录下 
            FileInfo filetmpDir = new FileInfo(tmpFilePath);
            filetmpDir.MoveTo(fileDir);

            //剪切过后，image的url需要重新指定至新路径下,此时取相对路径
            imgCut.ImageUrl = GetDirectoryOfDate(false) + user.UserName + Convert.ToString(ViewState["ext"]);
        } 
        #endregion

        //#region 获取日期目录
        //string GetDirectoryOfDate(bool isTemp)
        //{
        //    string upload = "UploadFile";

        //    string temp = "Temp/User";
        //    if (!isTemp)
        //        temp = "User";

        //    string year = DateTime.Now.Year.ToString();
        //    string month = DateTime.Now.ToString("MM");
        //    string day = DateTime.Now.ToString("dd");

        //    string[] paras = new string[] { upload, temp, year, month, day };

        //    string directory = string.Format("/{0}/{1}/{2}/{3}/{4}/", paras);

        //    return directory;
        //} 
        //#endregion
    }
}